//package com.rui.study.micro.msgcenter.service.support;
//
//import com.rui.study.commons.model.BizException;
//import com.rui.study.commons.util.JsonUtil;
//import com.rui.study.micro.msgcenter.model.MailWrapper;
//import com.rui.study.micro.msgcenter.service.mail.MailService;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.amqp.core.Message;
//import org.springframework.amqp.core.MessageListener;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Service;
//
//import java.util.concurrent.ScheduledThreadPoolExecutor;
//import java.util.concurrent.ThreadFactory;
//import java.util.concurrent.TimeUnit;
//import java.util.concurrent.atomic.AtomicInteger;
//
//@Service("messageListener")
//public class DelayMessageListener implements MessageListener {
//
//    private static final Logger LOGGER = LoggerFactory.getLogger(DelayMessageListener.class);
//
//    private ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(4, new ThreadFactory() {
//        private AtomicInteger num = new AtomicInteger();
//        @Override
//        public Thread newThread(Runnable r) {
//            return new Thread(r, "Sending-" + num.getAndIncrement());
//        }
//    });
//
//    @Autowired
//    private MailService mailService;
//
//
//
//    @Override
//    public void onMessage(Message message) {
//        MailWrapper mailWrapper;
//        String body;
//        try {
//            body = new String(message.getBody());
//            LOGGER.info("Received a message from RabbitMq");
//            mailWrapper = JsonUtil.toObject(body, MailWrapper.class);
//            executor.execute(new SendingTask(mailWrapper));
//            LOGGER.info("Executed the 'SendingTask'");
//        } catch (Exception e) {
//            LOGGER.error("系统异常", e);
//        }
//    }
//
//
//    private class SendingTask implements Runnable {
//
//        private final Logger LOGGER = LoggerFactory.getLogger(SendingTask.class);
//
//        private MailWrapper mailWrapper;
//
//        public SendingTask(MailWrapper mailWrapper) {
//            this.mailWrapper = mailWrapper;
//        }
//
//        @Override
//        public void run() {
//            MailWrapper mailWrapper = this.mailWrapper;
//            try {
//                mailService.send(mailWrapper);
//            } catch (BizException e) {
//                String errMsg = e.getMessage();
//                LOGGER.info("{}, 10秒后重发...\n{}", errMsg, mailWrapper);
//                executor.schedule(new SendingTask(mailWrapper), 10, TimeUnit.SECONDS);
//            }
//        }
//    }
//}
